<?php

require_once PATH_CLASS.'commun.class.php';

class image extends base{
  
  const C_IMAGE_NORMAL    = "normal";
  const C_IMAGE_MEDIUM    = "medium";
  const C_IMAGE_MINIATURE = "miniature";
  
  const C_IMAGE_MEMBRE    = "membre";
  const C_IMAGE_EQUIPE    = "equipe";
  const C_IMAGE_MATCH     = "match";

  public static function createImage($filename,$dest,$width,$height){
    // Cacul des nouvelles dimensions
    list($width_orig, $height_orig, $type) = getimagesize($filename);

    $ratio_orig = $width_orig/$height_orig;

    if ($width/$height > $ratio_orig) {
       $width = $height*$ratio_orig;
    } else {
       $height = $width/$ratio_orig;
    }

    // Redimensionnement
    $image_p = imagecreatetruecolor($width, $height);
    $foncCreate = 'imagecreatefromjpeg';
    $foncSave   = 'imagejpeg';
    switch($type){
      case IMAGETYPE_GIF:
        $foncCreate = 'imagecreatefromgif';
        $foncSave   = 'imagegif';

        $im  =imagecreatefromgif($filename);

        // if the image has transparent color, we first extract the RGB value of it,
        // then use this color to fill the thumbnail image as the background. This color
        // is safe to be assigned as the new transparent color later on because it will
        // be filtered by imagecopyresize.
        $originaltransparentcolor = imagecolortransparent( $im );
        if(
            $originaltransparentcolor >= 0 // -1 for opaque image
            && $originaltransparentcolor < imagecolorstotal( $im )
            // for animated GIF, imagecolortransparent will return a color index larger
            // than total colors, in this case the image is treated as opaque ( actually
            // it is opaque )
        ) {
            $transparentcolor = imagecolorsforindex( $im, $originaltransparentcolor );
            $newtransparentcolor = imagecolorallocate(
                $image_p,
                $transparentcolor['red'],
                $transparentcolor['green'],
                $transparentcolor['blue']
            );
            // for true color image, we must fill the background manually
            imagefill( $image_p, 0, 0, $newtransparentcolor );
            // assign the transparent color in the thumbnail image
            imagecolortransparent( $image_p, $newtransparentcolor );
        }
        $quality = 100;
        break;
      case IMAGETYPE_JPEG:
        $foncCreate = 'imagecreatefromjpeg';
        $foncSave   = 'imagejpeg';
        $quality    = 100;
        break;
      case IMAGETYPE_PNG:
        $foncCreate = 'imagecreatefrompng';
        $foncSave   = 'imagepng';
        $quality    = 9;
        break;
    }
    $image = $foncCreate($filename);
    if($st = imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig)){
      //On contrôle si le répertoire existe
      $dir = dirname($dest);
      if(is_dir($dir) || ($st=mkdir($dir))){
        $st = $foncSave($image_p,$dest,$quality,PNG_NO_FILTER);
      }
    }

    imagedestroy($image);
    imagedestroy($image_p);
    return $st;
  }
  
  public static function getRepertoirePhoto($type){

    $dirs = commun::getParamObj('photos_dirs');
    $dir  = "images";

    if (isset($dirs->base)){
      $dir = $dirs->base;
    }

    if (isset($dirs->{$type})){
      $dir = "$dir/".$dirs->{$type}."/";
    } else {
      $dir = "$dir/$type/";
    }

    $dir = str_replace('$', $type, $dir);

    return $dir;

  }

  public static function getRepertoirePhotoMatch(match $match){

    $rep = self::getRepertoirePhoto(self::C_IMAGE_MATCH);
    
    $dir = sprintf($rep,$match->match_saison_id,$match->match_id);

    return $dir;
  }

  public static function getRepertoirePhotoMatchSaison(match $match){

    $rep = self::getRepertoirePhoto(self::C_IMAGE_MATCH);
    
    $rep = str_replace('/match_%d/', '/', $rep);
    $dir = sprintf($rep,$match->match_saison_id,0);

    return $dir;
  }
  
  
  public static function analyseUploadedImage($name,$type,AjaxResponse &$response){
    $ret = true;
    $imgPars = commun::getParamObj('images_pars');

    if(isset($_FILES[$type]) && !empty($_FILES[$type]['tmp_name'][$name]) ){
      $file     = $_FILES[$type]['name'][$name];
      $pathinfo = pathinfo($file);
      $file     = $_FILES[$type]['tmp_name'][$name];
      $size     = getimagesize($file);

      if($size===false){
        $response->addError(sprintf("L'image %s n'est pas une image valide",$_FILES[$type]['name'][$name]));
        $ret = false;
        return $ret;
      }

      if(in_array(strtolower($pathinfo['extension']),$imgPars->ext)){
          if($size[0]<$imgPars->size->min->width){
            $response->addError(sprintf("Taille minimale requise (%s) : %d (image : %d)","largeur",$imgPars->size->min->width,$size[0]));
            $ret = false;
          }
          if($size[0]>$imgPars->size->max->width){
            $response->addError(sprintf("Taille maximale dépassée (%s) : %d (image : %d)","largeur",$imgPars->size->max->width,$size[0]));
            $ret = false;
          }
          if($size[1]<$imgPars->size->min->height){
            $response->addError(sprintf("Taille minimale requise (%s) : %d (image : %d)","hauteur",$imgPars->size->min->height,$size[1]));
            $ret = false;
          }
          if($size[1]>$imgPars->size->max->height){
            $response->addError(sprintf("Taille maximale dépassée (%s) : %d (image : %d)","hauteur",$imgPars->size->max->height,$size[1]));
            $ret = false;
          }
          $poids = $_FILES[$type]['size'][$name];

          if($poids<$imgPars->weight->min){
            $response->addError(sprintf("Poids minimal requis : %d (image : %d)",$imgPars->weight->min,$poids));
            $ret = false;
          }
          if($poids>$imgPars->weight->max){
            $response->addError(sprintf("Poids maximal dépassé : %d (image : %d)",$imgPars->weight->max,$poids));
            $ret = false;
          }

      } else {
        $response->addError("Extension interdite, vous devez fournir une image au format " .implode(',',$imgPars->ext));
        $ret = false;
      }


    }

    return $ret;
  }
  
  
  
  public static function replaceUploadedImage($type,$name,$id,&$fileName='',$fileWithMiniature=false){
    $ret = false;
    $dir = self::getRepertoirePhoto($type);
    if(isset($_FILES[$type]) && !empty($_FILES[$type]['tmp_name'][$name]) ){
      if(isset($dir)){
        if($fileName!=''){
          $fileName = $dir.$fileName;
          if(is_file($fileName)){
            commun::DeleteFileOrDir($fileName,$fileWithMiniature);
          }
        }
        $mime       = $_FILES[$type]['type'][$name];
        $ext        = explode('/',$mime);
        $ext        = $ext[1]=='jpeg' ? 'jpg' : $ext[1];
        $fileName   = "$type-$id.$ext";
        $finalName  = $dir.$fileName;
        $ret = move_uploaded_file($_FILES[$type]['tmp_name'][$name], $finalName);
      }
    }
    return $ret;
  }

  private static function getCheminPhoto($root,$id,$ext,$size='',$pars=array()){
    $chemin = self::getRepertoirePhoto($root);
    if($size=='')
      $chemin = $chemin."$root-$id.$ext";
    else
      $chemin = $chemin."$size/$root-$id.$ext";
    return $chemin;
  }
  
  private static function getCheminPhotoMatch($root,$id,$ext,$size='',$pars=array()){
    global $param;
    try{
      $imagesSize = json_decode($param['images_size']);
      $match      = $id;
      $chemin     = self::getRepertoirePhotoMatch($match);
      
      $imageName = "";
      
      if(is_array($pars) && isset($pars['image_name'])){
        $imageName = basename($pars['image_name'],'.'.pathinfo($pars['image_name'],PATHINFO_EXTENSION));
      }
      
      if($size==''){
        $chemin = $chemin."$imageName.$ext";
      } else {
        $chemin = $chemin."$size/$imageName.$ext";
      }
      
      return $chemin;
    } catch(Exception $e){
      $e;
    }
  }  
  
  public static function getFileName($id,$size=self::C_IMAGE_NORMAL,$root=self::C_IMAGE_MEMBRE,$params=array()){
    global $param;

    if($size==self::C_IMAGE_NORMAL){
      $size = '';
    }
    
    $params = array_merge($params,array(
      'getCheminPhoto' => 'getCheminPhoto'
    ));

    if($root==self::C_IMAGE_MATCH){
      $params['getCheminPhoto'] = 'getCheminPhotoMatch';
    }
    
    $imagesSize     = json_decode($param['images_size']);

    if(!isset($imagesSize->{$size})){
      $size   = "";
      $sizeTb = "";
    } else {
      $sizeTb=$imagesSize->{$size};
    }
    
    if(isset($imagesSize->{$root}) && isset($imagesSize->{$root}->{$size})){
      $sizeTb = $imagesSize->{$root}->{$size};
    }
    
    $trouve=false;
    foreach(array('jpg','jpeg','gif','png') as $ext){
			for($i=1;$i<=2;$i++){
				if($i==2) $ext = strtoupper($ext);
				//$filename = self::getRepertoirePhoto($root)."$root-$id.$ext";
				$filename = call_user_func(array('image', $params['getCheminPhoto']),$root,$id,$ext,'',$params);
				//$filename = $params['getCheminPhoto']($root,$id,$ext,'');
				//echo "$filename<br />";
				if(file_exists($filename)){
					$trouve=true;
					
					//Existe elle pour la taille voulue
					//$filename2 = self::getRepertoirePhoto($root)."$size/$root-$id.$ext";
					//$filename2 = $params['getCheminPhoto']($root,$id,$ext,$size);
					$filename2 = call_user_func(array('image', $params['getCheminPhoto']),$root,$id,$ext,$size,$params);

					if($size!=self::C_IMAGE_NORMAL && !file_exists($filename2)){
						$trouve = self::createImage($filename,$filename2,$sizeTb->width,$sizeTb->height);
					}

					break;
				} else {
				//	echo "nope<br />";
				}
				if($trouve) break;
			}
			if($trouve) break;
    }

    if($trouve==true){
      return $filename2;
    } else {
      switch($root){
      case 'equipe':
      case 'membre':
        if($id!=0){
          return self::getFileName(0,$size,$root,$params);
        } else {
          return self::getRepertoirePhoto($root)."$size/$root-0.gif";
        }
      default:
        return './images/blank.gif';
      }
      
    }
  }
  
  public static function getDynImgHTML($id,$what=self::C_IMAGE_MEMBRE,$pars=array()){

     $def = array(
          "class"=>""
         ,"size"=>self::C_IMAGE_NORMAL
         ,'addCacheByPass' =>true
         ,'viewer' =>null
     );

    $p = array_merge($def,$pars);

    $src= self::getFileName($id,$p['size'],$what,$pars);
    $src1=$src;

    $src .= $p['addCacheByPass'] == true ? '?cbp='.time() : '';
    $more=array();
    if(isset($p['class'])){
      $mode[]='class="'.$p['class'].'"';
    }
    
    $ret = sprintf('<img src="%s" %s/>',$src,join(' ',$more));
    
    if(isset($p['viewer'])){
      $src=self::getFileName($id,self::C_IMAGE_NORMAL,$what,$pars);
      if($src!=$src1){
        $ret=sprintf('<a href="%s" class="fancybox" rel="">%s</a>',$src,$ret);
      }
    }

    return $ret;
  }
  
  public static function outputImageBlank($width=1,$height=1,$red=0xFF,$green=0xFF,$blue=0xFF){
    $res    = imagecreate($width, $height);
    $color  = imagecolorallocate($res,$red,$green,$blue);
    $ret    = imagecolortransparent($res,$color);
    $ret    = imagegif($res);
  }
  
  
  static function getMembreImage($id,$size=self::C_IMAGE_NORMAL,$pars=array()){
    $p = array_merge(array("size"=>$size),$pars);
    $img = self::getDynImgHTML($id,self::C_IMAGE_MEMBRE,$p);
    return $img;
  }

  static function getEquipeImage($id,$size=self::C_IMAGE_NORMAL,$pars=array()){
    $p = array_merge(array("size"=>$size),$pars);
    $img = self::getDynImgHTML($id,self::C_IMAGE_EQUIPE,$p);
    return $img;
  }
  
  static $imageParams = '';
  
  static function isImage($fileName){
    $ret = false;
    
    if(empty(self::$imageParams)){
      self::$imageParams = commun::getParamObj('images_pars');
    }
    
    $params     = self::$imageParams;
    $fileName  = strtolower($fileName);
    
    if(in_array(pathinfo($fileName,PATHINFO_EXTENSION),$params->ext)){
      $ret=true;
    }

    return $ret;
  }

    static function isCredit($fileName){
    $ret = false;
    
    if($fileName=='credits.txt'){
      $ret=true;
    }

    return $ret;
  }

  static function getImageSize($size=self::C_IMAGE_MINIATURE,$type=0){
    $pars = commun::getParamObj('images_size');
    $ret = array('width'=>0,'height'=>0);
    if($pars && isset($pars->$size)){
      $ret = $pars->$size;
    }
    
    if($pars && isset($pars->{$type}) && isset($pars->{$type}->{$size})){
      $ret = $pars->{$type}->{$size};
    }
    return $ret;
  }
  
  static function getMatchImage($match_id,$image_name,$size=self::C_IMAGE_MINIATURE,$pars=array()){
    $match = ($match_id instanceof match ? $match_id : match::getMatch($match_id));
    if($match){
      $p = array_merge(array("size"=>$size,"image_name"=>$image_name),$pars);
      $img = self::getFileName($match,$size,self::C_IMAGE_MATCH,$p);
      return $img;      
    }
  }
  
  static function outputMatchImage($match_id,$image_name,$size=self::C_IMAGE_MINIATURE,$pars=array()){
    $match = ($match_id instanceof match ? $match_id : match::getMatch($match_id));
    if($match){
      $p = array_merge(array("size"=>$size,"image_name"=>$image_name),$pars);
      $img = self::getFileName($match,$size,self::C_IMAGE_MATCH,$p);
      flush();
      if($img!='./images/blank.gif'){
        @readfile($img);
      }
    }
  }
  
  
  static function getMatchImages($id){
    
    if($id instanceof match){
      $match = $id;
    } else {
      $match = match::getMatch($id);
    }
    
    $rep = self::getRepertoirePhotoMatch($match);
    
//    if(!empty($rep)){
//      $rep = $rep.sprintf("saison_%d/match_%d",$match->match_saison_id,$match->match_id);
//    }
    
    $credits[]    = '&copy; LOLITA';
    $creditsTb    = array();
   
    if(is_dir($rep)){
      $imagesTb = scandir($rep);
    } else {
      $imagesTb = false;
    }
    
    if($imagesTb===FALSE){
      $images = array();
    } else {
      $images   = array_filter($imagesTb, array(__CLASS__, 'isImage'));
      $creditsTb  = array_filter($imagesTb, array(__CLASS__, 'isCredit'));
    }
    
    if(count($creditsTb)>0){
      foreach($creditsTb as $credit){
        $credits[] = file_get_contents($rep.$credit);
      }
    } else {
      // On recherche à la racin de la saison
      $file = self::getRepertoirePhotoMatchSaison($match).'credits.txt';
      //if(is_file($file)){
        $cred = @file_get_contents($file);
        if($cred!==false && $cred!=''){
          $credits[]=$cred;
        }
      //}
    }
    
    $credits[] = '1993 - '.date('Y');
    
    $cnt = count($images);
    if($cnt){
      foreach($images as $key=>$item){
        $images[$key] = $rep.'/'.$item;
      }
    }
    
    if($cnt!=$match->match_has_image){
      $match->updateHasImage($cnt);
    }
    
    $obj = new stdClass();
    $obj->images  = $images;
    $obj->credits = $credits;
    $obj->path    = $rep;
    
    return $obj;
  }
}

